<template>
  <div class="w-full h-full overflow-hidden relative bg-[--bottomBackground]" :class="{ 'position_r': true, 'loadedHeight': loading }" v-loading="loading" :element-loading-text="loadingText" :element-loading-background="!!loadingText ? 'rgba(255, 255, 255, 0.8)' : 'rgba(122, 122, 122, 0.8)'">
    <el-button
      v-if="source && downloadShow"
      class="bg-[--system-primary-color] text-white"
      @click="download"
    >
      <span class="iconfont icon-xiazai" />
      下载
    </el-button>
    <VuePdfEmbed 
      v-show="!loading && !elEmptyShow" 
      @loading-failed="loadingFailedFn" 
      :source="source" 
      @loaded="loadedFn" 
      :scale="2.2"
      class="vue-pdf-embed absolute top-0 left-0 right-0 bottom-0"
    />
    <el-empty v-if="elEmptyShow" description="文件加载失败,请稍后重试..." />
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, getCurrentInstance, watch, PropType } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'
import { createLoadingTask } from 'vue3-pdfjs/esm' // 获得总页数
import { ElMessage } from 'element-plus'
import { downloadFile } from '@/utils/utilFn'

export default defineComponent({
  components: {
    VuePdfEmbed
  },
  props: {
    source: {
      type: Object as PropType<object | string>,
      require: true,
    },
    downloadShow: {
      type: Boolean,
      default: false
    },
    fileNmae: {
      type: String,
      default: '知识文档'
    },
  },
  setup(props, { emit }) {
    const { proxy } = getCurrentInstance() as any;
    const state = reactive({
      source: '' as object | string, //预览pdf文件地址
      loading: false,
      loadingText:'pdf文件数据加载中...',
      elEmptyShow: false,
    })
    // 文件流转换
    const getObjectURL = (data: any) => {
      if (!data) {
        state.source = ''
        return
      }
      let url = ''
      let file = new Blob([data], { type: 'application/pdf;chartset=utf-8' })
      if (window.URL.createObjectURL != undefined) {
        // 通用
        url = window.URL.createObjectURL(file)
      } else if (window.webkitURL != undefined) {
        // 兼容谷歌
        try {
          url = window.webkitURL.createObjectURL(file)
        } catch (error) {
          ElMessage.error('暂不支持谷歌浏览器')
        }
      } else if (window.URL != undefined) {
        // 兼容其他
        try {
          url = window.URL.createObjectURL(file)
        } catch (error) {
          ElMessage.error('暂不支持该浏览器')
        }
      }
      // 将转化后url赋值
      state.source = url
    }
    const download = () => {
      downloadFile(props?.source, 'pdf', props.fileNmae + '.pdf')
    }
    // 文件加载成功
    const loadedFn = () => {
      try{
        // 事件处理程序
        state.elEmptyShow = false
      }catch(err){
        // 错误事件处理程序（报错时执行）
        console.error(err);
      }finally{
      // 事件处理程序（报错或正常都会执行）
        state.loading = false
      }
    }
    // 文件加载失败
    const loadingFailedFn = () => {
      try{
        // 事件处理程序
        state.elEmptyShow = true
      }catch(err){
        // 错误事件处理程序（报错时执行）
        console.error(err);
      }finally{
        // 事件处理程序（报错或正常都会执行）
        state.loading = false
      }
    }
    watch(
      () => props.source, //红头url
      (n: any, o: any) => {
        state.loading = true
        if(!n || (Array.isArray(n) && n.length === 0) || (Object.prototype.toString.call(n) === '[object Object]' && Reflect.ownKeys(n).length === 0)) return
        getObjectURL(n)
      },
      {
        immediate: true,
        deep: true
      }
    )
    onMounted(() => {})
    return {
      ...toRefs(state),
      download,
      loadedFn,
      loadingFailedFn
    }
  }
})
</script>

<style lang="scss" scoped>
.loadedHeight {
  height: 50vh;
}
.vue-pdf-embed {
  text-align: center;
  width: 842px;
  border: 1px solid #e5e5e5;
  margin: 0 auto;
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}
:deep(.textLayer) {
  padding-bottom: 10rpx !important;
  border-top: 1px solid #000 !important;
  border-bottom: 1px solid #000 !important;
}
.xiazai {
  top: 0;
  right: 5rem;
}
</style>
